package com.kongchengji.zhanguafou.quartz;

import com.kongchengji.zhanguafou.constant.WxInfo;
import com.kongchengji.zhanguafou.dao.QuartzDAO;
import com.kongchengji.zhanguafou.dao.StationDAO;
import com.kongchengji.zhanguafou.domain.QuartzDO;
import com.kongchengji.zhanguafou.domain.StationInfoDO;
import com.kongchengji.zhanguafou.utils.FormatTimeUtil;
import com.kongchengji.zhanguafou.utils.GetStationUtil;
import okhttp3.*;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.io.*;

/**
 * 监控网站站点任务类
 */
@Component // 此注解必加
@EnableScheduling // 此注解必加
public class ListenStationScheduleTask implements Job, Serializable {
    @Autowired
    StationDAO stationDAO;
    @Autowired
    private QuartzDAO quartzDAO;
    private QuartzDO quartzDO;
    //站点网址
    private String url;
    //用户id
    private String openId;
    //告警信息
    private String message;
    //告警级别
    private String level;
    //站点名称
    private String name;

    @Override
    public void execute(JobExecutionContext context) {
        try {
            //获得传递过来的参数
            JobDataMap dataMap = context.getJobDetail().getJobDataMap();
            QuartzDO quartz = (QuartzDO) dataMap.get("quartz");
            url = quartz.getUrl();
            openId = quartz.getOpenId();
            name = quartz.getName();
            String jobName = quartz.getJobName();
            //通过任务的唯一标识得到是否是第一次发送信息
            Example example = new Example(QuartzDO.class);
            example.createCriteria().andEqualTo("jobName",jobName);
            quartzDO = quartzDAO.selectOneByExample(example);
            //获得站点还能否打开的标识
            boolean isOpen = getStationFlag();
            if(!isOpen){
                sendMsg();
            }
            //站点不能打开同时不是第一次发送恢复通知
            if(isOpen && quartzDO.getFirst() == 0){
                sendMsg();
            }
        }
        catch (Exception e) {
           e.printStackTrace();
        }
    }

    /**
     * 获得域名,排除协议头
     *
     * @param url 网址
     * @return 返回域名
     */
    private String getDomain(String url) {
        if (url.startsWith("http")) {
            url = url.substring(url.indexOf("//") + 2);
        }
        return url;
    }

    /**
     * 获得站点是否能打开的标识，false为打不开，true为能打开
     * @return
     */
    private boolean getStationFlag() {
        StationInfoDO stationInfoDO = GetStationUtil.get(url);
        if (stationInfoDO != null) {
            if (stationInfoDO.getCode() != 200) {
                message = "您的网站无法打开";
                level = "严重告警";
                return false;
            }
        } else {
            message = "您的网站无法打开";
            level = "严重告警";
            return false;
        }
        return true;
    }


    private String sendMsg() {
        String json = buildMsg();
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + WxInfo.accessToken.getToken())//请求的url
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    private String buildMsg() {
        String jsonMsg;
        //任务第一次发送消息
        if (quartzDO.getFirst() == 1) {
            //修改数据库中first字段中的值
            quartzDO.setFirst(0);
            quartzDAO.updateByPrimaryKey(quartzDO);
            jsonMsg = "{" +
                    "           \"touser\":\"" + openId + "\"," +
                    "           \"template_id\":\"ZycQT_g3UEMOAXPAfNZV1UdxZRcxa-1AHjztxQGJya4\"," +
                    "           \"data\":{" +
                    "                   \"first\": {" +
                    "                       \"value\":\"站点告警通知\"," +
                    "                       \"color\":\"#FF0000\"" +
                    "                   }," +
                    "                   \"keyword1\":{" +
                    "                       \"value\":\"" + name + "\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword2\": {" +
                    "                       \"value\":\"" + url + "\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword3\":{" +
                    "                       \"value\":\"" + message + "\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword4\":{" +
                    "                       \"value\":\"" + level + "\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword5\":{" +
                    "                       \"value\":\"" + FormatTimeUtil.getFormatTime() + "\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"remark\": {" +
                    "                       \"value\":\"请及时处理\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }" +
                    "           }" +
                    "       }";
        } else {
            //修改数据库中first字段的值
            quartzDO.setFirst(1);
            quartzDAO.updateByPrimaryKey(quartzDO);
            jsonMsg = "{" +
                    "           \"touser\":\"" + openId + "\"," +
                    "           \"template_id\":\"OvBfi43054FtahoVfHVLtvjh4vdsawzPtFdhFYqpMO0\"," +
                    "           \"data\":{" +
                    "                   \"first\": {" +
                    "                       \"value\":\"你的站点"+quartzDO.getName()+"已经恢复正常\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword1\":{" +
                    "                       \"value\":\"可能是网络原因\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword2\": {" +
                    "                       \"value\":\"" + FormatTimeUtil.getFormatTime() + "\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"remark\":{" +
                    "                       \"value\":\"站挂否持续为你服务\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }" +
                    "           }" +
                    "       }";
        }
        return jsonMsg;
    }

}
